package com.example.aggregationmode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@RestController
public class TestController {
    @Autowired
    ApplicationContext applicationContext;

    /**
     * 对外提供一个聚合方法，对于新增功能只需实现聚合接口，不用修改原来的方法
     *
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("get")
    public List<String> get() throws ExecutionException, InterruptedException {
        // 获取Aggregation的所有实现
        Map<String,Aggregation> allBeans= applicationContext.getBeansOfType(Aggregation.class);

        ExecutorService executorService= Executors.newCachedThreadPool();

        // 使用futureList接受执行结果
        ArrayList<Future<String>> futureList=new ArrayList<>();

        // 提交任务到线程池
        for (Aggregation aggregation:allBeans.values()){
            Future<String> future=executorService.submit(aggregation);
            futureList.add(future);
        }
        executorService.shutdown();

        List<String>res=new ArrayList<>();
        // 汇总结果
        for (Future<String> f : futureList) {
            res.add(f.get());
        }

        return res;
    }
}
